<template>
  <div
    class="upload-container flex-row-center-center"
    :style="customStyle"
    :class="{ 'not-image': !postModel[imgKey] }"
    @click="handleClick"
  >
    <input type="file" accept=".png,.jpg,.jpeg" style="display: none" :id="uploadId" />
    <span v-if="!postModel[imgKey]">点击上传{{ placeholder }}</span>
    <img v-else alt="img" :src="postModel[imgKey]" />
    <Loading :loading="uploading" :absolute="true" tip="正在上传～" />
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import mcApi from 'mc-c2b2m-operator-api';
  import { Loading } from '@/components/Loading';

  const { SysModule } = mcApi;
  const { UploadApi } = SysModule;

  defineProps({
    // 自定义样式，主要是上传区域的宽高
    customStyle: {
      type: Object,
      default: () => {
        return {
          width: '343px',
          height: '170px',
        };
      },
    },
    // 提示语
    placeholder: {
      type: String,
    },
    // 表单数据源
    postModel: {
      required: true,
      type: Object,
      default: () => {
        return {};
      },
    },
    // 图片资源的key
    imgKey: {
      default: 'url',
      type: String,
      required: true,
    },
  });

  const uploading = ref(false);
  const uploadId = new Date().getTime() + '';
  const emits = defineEmits(['file']);
  function handleClick() {
    const ele = document.getElementById(uploadId) as HTMLInputElement;
    ele.click();
    ele.addEventListener('change', handleChange);
  }
  function handleChange(e: any) {
    const file = e.target.files?.[0];
    if (!file) return;
    uploading.value = true;
    UploadApi.uploadFile({ file })
      .then((res) => {
        emits('file', res);
      })
      .finally(() => {
        const ele = document.getElementById(uploadId) as HTMLInputElement;
        ele.value = '';
        uploading.value = false;
      });
  }
</script>

<style scoped lang="less">
  .upload-container {
    cursor: pointer;

    img {
      width: 100%;
      height: 100%;
    }
  }

  .not-image {
    background-color: #fafafa;
    border: 2px dashed #d9d9d9;
  }
</style>
